#include "timer.h"

typedef struct _timeout_data {
	struct timeval time;
	void *callup_ctx;
	timeout_data_handler callup_handler;
} timeout_data;

static timeout_data timeout;

int get_time(struct timeval *tm)
{
	int res;
	res = gettimeofday(tm, NULL);
	return res;
}

int register_timeout(long secs, long usecs,timeout_data_handler handler,void * ctx)
{
	memset(&timeout, 0, sizeof(timeout_data));
	
	if (get_time(&timeout.time)) {
		return -1;
	}

	timeout.time.tv_sec += secs;
	timeout.time.tv_usec += usecs;

	while (timeout.time.tv_usec >= 1000000) {
		timeout.time.tv_sec++;
		timeout.time.tv_usec -= 1000000;
	}

	timeout.callup_ctx = ctx;
	timeout.callup_handler = handler;

	return 0;
}

int cancel_timeout()
{
	memset(&timeout, 0, sizeof(timeout_data));
	return 0;
}

void timer_run()
{
	struct timeval now;	

	while(1) {
		if (get_time(&now))
			return;

		if (!time_before(&now, &timeout.time)) {
			void *ctx = timeout.callup_ctx;
			timeout_data_handler handler = timeout.callup_handler;
			cancel_timeout();
			handler(ctx);
		}
	}
}
